"""聊天历史记录管理模块"""
from typing import List, Dict, Optional
from datetime import datetime
import json

# 内存存储：使用字典存储会话历史
# 结构：{session_id: [{"role": "user|assistant", "content": "...", "timestamp": ...}, ...]}
_chat_history: Dict[str, List[Dict]] = {}

# 默认会话ID
DEFAULT_SESSION_ID = "default"


def get_history(session_id: str = DEFAULT_SESSION_ID, max_messages: Optional[int] = None) -> List[Dict]:
    """
    获取会话历史记录
    
    Args:
        session_id: 会话ID，默认为 "default"
        max_messages: 最大消息数量，None表示返回所有消息
        
    Returns:
        历史消息列表
    """
    if session_id not in _chat_history:
        return []
    
    history = _chat_history[session_id]
    
    if max_messages is not None:
        # 返回最近N条消息
        return history[-max_messages:] if len(history) > max_messages else history
    
    return history.copy()


def add_message(session_id: str, role: str, content: str, timestamp: Optional[float] = None) -> None:
    """
    添加消息到历史记录
    
    Args:
        session_id: 会话ID
        role: 角色 ("user" 或 "assistant")
        content: 消息内容
        timestamp: 时间戳，None则使用当前时间
    """
    if session_id not in _chat_history:
        _chat_history[session_id] = []
    
    if timestamp is None:
        timestamp = datetime.now().timestamp()
    
    _chat_history[session_id].append({
        "role": role,
        "content": content,
        "timestamp": timestamp
    })


def clear_history(session_id: str = DEFAULT_SESSION_ID) -> None:
    """
    清空指定会话的历史记录
    
    Args:
        session_id: 会话ID
    """
    if session_id in _chat_history:
        _chat_history[session_id] = []


def get_all_sessions() -> List[str]:
    """
    获取所有会话ID列表
    
    Returns:
        会话ID列表
    """
    return list(_chat_history.keys())


def get_history_count(session_id: str = DEFAULT_SESSION_ID) -> int:
    """
    获取指定会话的消息数量
    
    Args:
        session_id: 会话ID
        
    Returns:
        消息数量
    """
    if session_id not in _chat_history:
        return 0
    return len(_chat_history[session_id])

